import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as path;
import 'package:image_picker/image_picker.dart';
import '../models/user_info.dart';
import '../serve/file_serve.dart';
import '../widgets/simple_knowledge_graph_widget.dart';
import 'knowledge_graph_page.dart';

class IdentityPage extends StatefulWidget {
  final String appDataDir;
  final UserInfo userInfo;
  final Function(UserInfo) onUpdateUserInfo;
  final FileServe fileServe;

  const IdentityPage({
    Key? key,
    required this.appDataDir,
    required this.userInfo,
    required this.onUpdateUserInfo,
    required this.fileServe,
  }) : super(key: key);

  @override
  _IdentityPageState createState() => _IdentityPageState();
}

class _IdentityPageState extends State<IdentityPage> with TickerProviderStateMixin {
  late TextEditingController _nicknameController;
  late TextEditingController _descriptionController;
  late List<String> _selectedTags;
  String? _avatarPath;
  bool _isLoading = true;
  late AnimationController _headerAnimationController;
  late AnimationController _contentAnimationController;
  late Animation<double> _headerFadeAnimation;
  late Animation<Offset> _headerSlideAnimation;
  late Animation<double> _contentFadeAnimation;
  
  final List<String> _availableTags = [
    '人工智能专业学生',
    '计算机程序爱好者',
    '科技行业从业者',
    '知识管理爱好者',
    '自然语言处理研究者',
  ];

  @override
  void initState() {
    super.initState();
    _nicknameController = TextEditingController(text: widget.userInfo.nickname);
    _descriptionController = TextEditingController(text: widget.userInfo.description ?? '');
    _selectedTags = List.from(widget.userInfo.identityTags);
    
    // 初始化动画控制器
    _headerAnimationController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 800),
    );
    _contentAnimationController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 1000),
    );
    
    _headerFadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _headerAnimationController, curve: Curves.easeOut),
    );
    _headerSlideAnimation = Tween<Offset>(begin: Offset(0, -0.3), end: Offset.zero).animate(
      CurvedAnimation(parent: _headerAnimationController, curve: Curves.easeOut),
    );
    _contentFadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _contentAnimationController, curve: Interval(0.2, 1.0, curve: Curves.easeOut)),
    );
    
    _loadAvatar();
  }

  Future<void> _loadAvatar() async {
    try {
      final avatarPath = await widget.fileServe.getUserAvatarPath();
      if (mounted) {
        setState(() {
          _avatarPath = avatarPath;
          _isLoading = false;
        });
        
        // 启动动画
        _headerAnimationController.forward();
        await Future.delayed(Duration(milliseconds: 300));
        _contentAnimationController.forward();
      }
    } catch (e) {
      print('加载头像失败: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
        
        // 启动动画
        _headerAnimationController.forward();
        await Future.delayed(Duration(milliseconds: 300));
        _contentAnimationController.forward();
      }
    }
  }

  Future<void> _pickImage() async {
    try {
      final ImagePicker picker = ImagePicker();
      final XFile? image = await picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 512,
        maxHeight: 512,
        imageQuality: 85,
      );

      if (image != null) {
        final bytes = await image.readAsBytes();
        final extension = image.path.split('.').last.toLowerCase();
        
        // 删除旧头像
        await widget.fileServe.deleteUserAvatar();
        
        // 保存新头像
        final success = await widget.fileServe.saveUserAvatar(bytes, extension);
        
        if (success && mounted) {
          final newAvatarPath = await widget.fileServe.getUserAvatarPath();
          setState(() {
            _avatarPath = newAvatarPath;
          });
          _showSuccessMessage('头像更新成功');
        }
      }
    } catch (e) {
      print('选择图片失败: $e');
      if (mounted) {
        _showErrorMessage('选择图片失败: $e');
      }
    }
  }

  @override
  void dispose() {
    _nicknameController.dispose();
    _descriptionController.dispose();
    _headerAnimationController.dispose();
    _contentAnimationController.dispose();
    super.dispose();
  }

  Future<void> _saveUserInfo() async {
    final newUserInfo = UserInfo(
      nickname: _nicknameController.text,
      identityTags: _selectedTags,
      description: _descriptionController.text.trim().isEmpty ? null : _descriptionController.text.trim(),
    );
    
    try {
      final success = await widget.fileServe.saveUserInfo(newUserInfo.toJson());
      if (success) {
        widget.onUpdateUserInfo(newUserInfo);
        if (mounted) {
          _showSuccessMessage('保存成功');
        }
      } else {
        if (mounted) {
          _showErrorMessage('保存失败');
        }
      }
    } catch (e) {
      print('保存用户信息失败: $e');
      if (mounted) {
        _showErrorMessage('保存失败: $e');
      }
    }
  }

  void _showSuccessMessage(String message) {
        ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green[400],
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        margin: EdgeInsets.all(16),
      ),
    );
  }

  void _showErrorMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red[400],
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        margin: EdgeInsets.all(16),
      ),
    );
  }

  void _showAddTagDialog() {
    final TextEditingController tagController = TextEditingController();
    
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
          title: Row(
            children: [
              Container(
                padding: EdgeInsets.all(8),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                  ),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Icon(Icons.add, color: Colors.white, size: 20),
              ),
              SizedBox(width: 12),
              Text('添加标签'),
            ],
          ),
          content: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [Color(0xFFF8F9FA), Color(0xFFE9ECEF)],
              ),
              borderRadius: BorderRadius.circular(16),
            ),
            child: TextField(
            controller: tagController,
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
            decoration: InputDecoration(
              hintText: '请输入标签内容',
                hintStyle: TextStyle(color: Colors.grey[500]),
              border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide.none,
              ),
                contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 16),
                filled: true,
                fillColor: Colors.transparent,
            ),
            autofocus: true,
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text('取消', style: TextStyle(color: Colors.grey[600])),
            ),
            Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                ),
                borderRadius: BorderRadius.circular(12),
              ),
              child: TextButton(
              onPressed: () {
                final newTag = tagController.text.trim();
                if (newTag.isNotEmpty) {
                  setState(() {
                    _selectedTags.add(newTag);
                  });
                  _saveUserInfo();
                }
                Navigator.pop(context);
              },
                child: Text('确定', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600)),
              ),
            ),
          ],
        );
      },
    );
  }

  void _showDeleteTagDialog(String tag) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
          title: Row(
            children: [
              Container(
                padding: EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.red[100],
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Icon(Icons.delete_outline, color: Colors.red[600], size: 20),
              ),
              SizedBox(width: 12),
              Text('删除标签'),
            ],
          ),
          content: Text('确定要删除标签"$tag"吗？'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text('取消', style: TextStyle(color: Colors.grey[600])),
            ),
            Container(
              decoration: BoxDecoration(
                color: Colors.red[400],
                borderRadius: BorderRadius.circular(12),
              ),
              child: TextButton(
              onPressed: () {
                setState(() {
                  _selectedTags.remove(tag);
                });
                _saveUserInfo();
                Navigator.pop(context);
              },
                child: Text('删除', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600)),
              ),
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      body: _isLoading 
          ? _buildLoadingScreen()
          : _buildIdentityScreen(),
    );
  }

  Widget _buildLoadingScreen() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF667eea),
            Color(0xFF764ba2),
          ],
        ),
      ),
      child: Center(
                  child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
              width: 80,
              height: 80,
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                strokeWidth: 3,
              ),
            ),
            SizedBox(height: 24),
            Text(
              '加载用户信息...',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18,
                fontWeight: FontWeight.w600,
              ),
                      ),
                    ],
                  ),
                ),
    );
  }

  Widget _buildIdentityScreen() {
    return CustomScrollView(
      slivers: [
        // 美化的顶部区域
        SliverToBoxAdapter(
          child: _buildBeautifulHeader(),
        ),
        // 表单内容区域
        SliverToBoxAdapter(
          child: _buildFormContent(),
        ),
      ],
    );
  }

  Widget _buildBeautifulHeader() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF667eea),
            Color(0xFF764ba2),
          ],
        ),
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(32),
          bottomRight: Radius.circular(32),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 20,
            offset: Offset(0, 10),
          ),
        ],
      ),
      child: SafeArea(
        child: FadeTransition(
          opacity: _headerFadeAnimation,
          child: SlideTransition(
            position: _headerSlideAnimation,
            child: Padding(
              padding: EdgeInsets.fromLTRB(24, 20, 24, 40),
      child: Column(
        children: [
                  // 头部标题
          Row(
            children: [
                      Container(
                        padding: EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.2),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Icon(
                          Icons.person,
                          color: Colors.white,
                          size: 24,
                        ),
                      ),
                      SizedBox(width: 12),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
              Text(
                              '个人身份',
                style: TextStyle(
                                fontSize: 28,
                                fontWeight: FontWeight.w800,
                                color: Colors.white,
                                letterSpacing: 0.5,
                              ),
                            ),
                            Text(
                              '管理你的个人信息和身份标签',
                  style: TextStyle(
                                fontSize: 14,
                                color: Colors.white.withOpacity(0.8),
                                fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
                      ),
                    ],
                  ),
                  
                  SizedBox(height: 32),
                  
                  // 头像区域
                  _buildAvatarSection(),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildAvatarSection() {
    return Column(
      children: [
        // 头像
        GestureDetector(
          onTap: _pickImage,
          child: Stack(
          children: [
            Container(
                width: 120,
                height: 120,
              decoration: BoxDecoration(
                  color: Colors.white,
                shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.15),
                      blurRadius: 30,
                      offset: Offset(0, 15),
                    ),
                  ],
                ),
                child: ClipOval(
                  child: _avatarPath != null
                      ? Image.file(
                          File(_avatarPath!),
                          width: 120,
                          height: 120,
                          fit: BoxFit.cover,
                        )
                      : Container(
                          width: 120,
                          height: 120,
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              colors: [Color(0xFFE8EAF6), Color(0xFFC5CAE9)],
                            ),
                          ),
                          child: Icon(
                            Icons.person,
                            size: 50,
                            color: Colors.grey[600],
                          ),
                        ),
                ),
              ),
              Positioned(
                bottom: 0,
                right: 0,
                child: Container(
                  padding: EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                    ),
                    shape: BoxShape.circle,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.2),
                        blurRadius: 8,
                        offset: Offset(0, 4),
                      ),
                    ],
                  ),
                  child: Icon(
                    Icons.camera_alt,
                    color: Colors.white,
                          size: 16,
                        ),
                          ),
                        ),
                      ],
                    ),
        ),
        
        SizedBox(height: 16),
        
        // 昵称显示
        Container(
          padding: EdgeInsets.symmetric(horizontal: 24, vertical: 12),
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.15),
            borderRadius: BorderRadius.circular(20),
            border: Border.all(color: Colors.white.withOpacity(0.2)),
          ),
          child: Text(
            _nicknameController.text.isEmpty ? '未设置昵称' : _nicknameController.text,
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildFormContent() {
    return FadeTransition(
      opacity: _contentFadeAnimation,
      child: Container(
        margin: EdgeInsets.all(24),
        padding: EdgeInsets.all(28),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(32),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.08),
              blurRadius: 30,
              offset: Offset(0, 20),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildSectionTitle('基本信息', Icons.info_outline),
            SizedBox(height: 20),
            _buildNicknameInput(),
            SizedBox(height: 20),
            _buildDescriptionInput(),
            
            SizedBox(height: 32),
            
            _buildSectionTitle('身份标签', Icons.local_offer_outlined),
            SizedBox(height: 20),
            _buildTagsSection(),
            
            SizedBox(height: 32),
            
            _buildSaveButton(),
            
            SizedBox(height: 24),
            
            _buildKnowledgeGraphSection(),
          ],
        ),
      ),
    );
  }

  Widget _buildSectionTitle(String title, IconData icon) {
    return Row(
              children: [
                Container(
          padding: EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
              colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                    ),
            borderRadius: BorderRadius.circular(12),
                  ),
                  child: Icon(
            icon,
            color: Colors.white,
            size: 20,
          ),
        ),
        SizedBox(width: 12),
                Text(
          title,
                  style: TextStyle(
                    fontSize: 20,
            fontWeight: FontWeight.w700,
            color: Colors.grey[800],
          ),
        ),
      ],
    );
  }

  Widget _buildNicknameInput() {
    return Container(
                  decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Color(0xFFF8F9FA), Color(0xFFE9ECEF)],
        ),
                    borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: Offset(0, 4),
                ),
              ],
            ),
      child: TextField(
        controller: _nicknameController,
        style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
        decoration: InputDecoration(
          labelText: '昵称',
          hintText: '💭 请输入你的昵称...',
          hintStyle: TextStyle(color: Colors.grey[500]),
          labelStyle: TextStyle(color: Colors.grey[600], fontWeight: FontWeight.w600),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(20),
            borderSide: BorderSide.none,
          ),
          contentPadding: EdgeInsets.symmetric(horizontal: 24, vertical: 20),
          filled: true,
          fillColor: Colors.transparent,
        ),
        onChanged: (value) {
          // 实时保存
          Future.delayed(Duration(milliseconds: 500), () {
            if (_nicknameController.text == value) {
              _saveUserInfo();
            }
          });
        },
      ),
    );
  }

  Widget _buildDescriptionInput() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Color(0xFFF8F9FA), Color(0xFFE9ECEF)],
        ),
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: Offset(0, 4),
          ),
        ],
      ),
      child: TextField(
        controller: _descriptionController,
        style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
        maxLines: 3,
        decoration: InputDecoration(
          labelText: '个人描述',
          hintText: '📝 介绍一下你自己...',
          hintStyle: TextStyle(color: Colors.grey[500]),
          labelStyle: TextStyle(color: Colors.grey[600], fontWeight: FontWeight.w600),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(20),
            borderSide: BorderSide.none,
          ),
          contentPadding: EdgeInsets.symmetric(horizontal: 24, vertical: 20),
          filled: true,
          fillColor: Colors.transparent,
        ),
        onChanged: (value) {
          // 实时保存
          Future.delayed(Duration(milliseconds: 1000), () {
            if (_descriptionController.text == value) {
              _saveUserInfo();
            }
          });
        },
      ),
    );
  }

  Widget _buildTagsSection() {
    return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
        // 添加标签按钮
                  Container(
          width: double.infinity,
                    decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xFFF8F9FA), Color(0xFFE9ECEF)],
            ),
            borderRadius: BorderRadius.circular(16),
            border: Border.all(color: Colors.grey[200]!, style: BorderStyle.solid, width: 2),
          ),
          child: Material(
            color: Colors.transparent,
            child: InkWell(
              onTap: _showAddTagDialog,
              borderRadius: BorderRadius.circular(16),
              child: Padding(
                padding: EdgeInsets.symmetric(vertical: 16, horizontal: 20),
                child: Row(
                        children: [
                          Container(
                      padding: EdgeInsets.all(6),
                            decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                        ),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Icon(Icons.add, color: Colors.white, size: 16),
                    ),
                    SizedBox(width: 12),
                    Text(
                      '添加新标签',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        color: Colors.grey[700],
                      ),
                    ),
                    Spacer(),
                    Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey[400]),
                  ],
                ),
                              ),
                            ),
                          ),
        ),
        
        SizedBox(height: 16),
        
        // 标签列表
        if (_selectedTags.isNotEmpty)
          Wrap(
            spacing: 12,
            runSpacing: 12,
            children: _selectedTags.map((tag) {
              return Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [Color(0xFFE3F2FD), Color(0xFFBBDEFB)],
                  ),
                  borderRadius: BorderRadius.circular(20),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.blue.withOpacity(0.1),
                      blurRadius: 8,
                      offset: Offset(0, 4),
                    ),
                  ],
                ),
                child: Material(
                  color: Colors.transparent,
                  child: InkWell(
                    onTap: () => _showDeleteTagDialog(tag),
                    borderRadius: BorderRadius.circular(20),
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                  Text(
                            tag,
                    style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                              color: Colors.blue[800],
                            ),
                          ),
                          SizedBox(width: 8),
                          Icon(
                            Icons.close,
                            size: 16,
                            color: Colors.blue[600],
              ),
            ],
          ),
        ),
                  ),
                ),
              );
            }).toList(),
          )
        else
          Container(
            width: double.infinity,
            padding: EdgeInsets.all(32),
          decoration: BoxDecoration(
              color: Colors.grey[50],
            borderRadius: BorderRadius.circular(16),
              border: Border.all(color: Colors.grey[200]!),
          ),
            child: Column(
            children: [
              Icon(
                  Icons.local_offer_outlined,
                  size: 48,
                  color: Colors.grey[400],
                ),
                SizedBox(height: 12),
              Text(
                  '还没有身份标签',
                style: TextStyle(
                    fontSize: 16,
                    color: Colors.grey[500],
                  fontWeight: FontWeight.w500,
                ),
              ),
                SizedBox(height: 8),
                Text(
                  '点击上方按钮添加你的第一个标签',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[400],
                  ),
                ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildSaveButton() {
    return Container(
      width: double.infinity,
      height: 56,
        decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Color(0xFF667eea), Color(0xFF764ba2)],
        ),
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Color(0xFF667eea).withOpacity(0.3),
            blurRadius: 20,
            offset: Offset(0, 10),
          ),
        ],
      ),
      child: ElevatedButton(
        onPressed: _saveUserInfo,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.transparent,
          foregroundColor: Colors.white,
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
        children: [
            Icon(Icons.save, size: 20),
            SizedBox(width: 8),
          Text(
              '保存信息',
            style: TextStyle(
              fontSize: 16,
                fontWeight: FontWeight.w700,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildKnowledgeGraphSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
                children: [
        _buildSectionTitle('知识图谱', Icons.account_tree_outlined),
            Spacer(),
            TextButton.icon(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => KnowledgeGraphPage(
                      fileServe: widget.fileServe,
                    ),
                  ),
                );
              },
              icon: Icon(Icons.fullscreen, size: 16),
              label: Text('查看详情'),
              style: TextButton.styleFrom(
                foregroundColor: Color(0xFF667eea),
                textStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
              ),
            ),
          ],
        ),
                  SizedBox(height: 20),
        GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => KnowledgeGraphPage(
                  fileServe: widget.fileServe,
                ),
              ),
            );
          },
          child: Container(
            height: 180, // 缩小高度
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xFFF8F9FA), Color(0xFFE9ECEF)],
            ),
            borderRadius: BorderRadius.circular(20),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.03),
                blurRadius: 8,
                offset: Offset(0, 4),
              ),
            ],
          ),
            child: Stack(
              children: [
                // 缩略图谱
                Padding(
                  padding: EdgeInsets.all(16),
            child: SimpleKnowledgeGraphWidget(
              fileServe: widget.fileServe,
                    width: double.infinity,
                    height: 148,
                    showLabels: false, // 缩略图不显示标签
                  ),
                ),
                // 覆盖层，提示点击
                Positioned(
                  bottom: 0,
                  left: 0,
                  right: 0,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          Colors.transparent,
                          Colors.black.withOpacity(0.6),
                        ],
                      ),
                      borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(20),
                        bottomRight: Radius.circular(20),
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.touch_app,
                          color: Colors.white,
                          size: 16,
                        ),
                        SizedBox(width: 8),
                        Text(
                          '点击查看完整知识图谱',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 14,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
} 